'''
幸孕星19母婴医疗险
'''
import sys

sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "幸孕星19母婴医疗险"

    # 生成产品数据
    def genProductInfo(self):
        plan = {
            # 年龄段 19 - 40
            "year": [str(i) for i in range(19, 41)],
            # 版本
            "plan": ["萌妈版", "辣妈版", "贵妇版"],
            # 生育险
            "birthSec": ["Y", "N"],
            # 单双胞胎 1 单胞胎 2 双胞胎
            "twins": ["1", "2"]

        }
        for v in product(plan["year"], plan["plan"], plan["birthSec"], plan["twins"]):

            planCode = self.FilterPlan( v )

            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(v[0], v[1], planCode, v[2], v[3]))
            self.mysql._conn.commit()
            print(domain[self.name]["insert_sql"].format(v[0], v[1], planCode, v[2], v[3]))

    # 过滤计划
    def FilterPlan(self,data):
        # 计划代码

        if data[1] == "萌妈版":
            # 有社保
            if data[2] == "Y" and data[3] == "1":

                planCode = "A"

                return planCode

            elif data[2] == "N" and data[3] == "1":

                planCode = "B"

                return planCode

            elif data[2] == "Y" and data[3] == "2":

                planCode = "C"

                return planCode

            else:

                planCode = "D"

                return planCode


        elif data[1] == "辣妈版":

            # 有社保
            if data[2] == "Y" and data[3] == "1":

                planCode = "E"

                return planCode

            elif data[2] == "N" and data[3] == "1":

                planCode = "F"

                return planCode

            elif data[2] == "Y" and data[3] == "2":

                planCode = "G"

                return planCode

            else:

                planCode = "H"

                return planCode

        else:
            # 有社保
            if data[2] == "Y" and data[3] == "1":

                planCode = "I"

                return planCode

            elif data[2] == "N" and data[3] == "1":

                planCode = "J"

                return planCode

            elif data[2] == "Y" and data[3] == "2":

                planCode = "K"

                return planCode

            else:

                planCode = "L"

                return planCode

    # 执行爬虫
    def requestJson(self, dt=None):

        data = {"policyData": {"paymentType": "5", "productCode": "XYX", "channelRequestString": ""}, "insuredData": [
            {"insuredNo": "0", "insuredBirthday": "{year}-01-01".format(year =  str(2019-int(dt["year"]))), "insuredMedicalInsurance": dt["birthSec"], "insuredSex": "F",
             "singleTwins": dt["twins"]}], "planData": [
            {"planMajor": "Y", "planPeriod": "1", "paymentPeriod": "1", "planUnits": "1", "useFlag": "Y",
             "insurantNo": "0", "benLevel": dt["planCode"], "planCode": "1058"}]}

        payload = json.dumps( data )

        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)

        if r.status_code == 200 and r.json()["result"] == "1":

            price = Helper.decimalParse( r.json()["stdPrem"] )

            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )

        else:

            # 任务执行失败
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            self.mysql.updateTask(data)

            print("产品价格更新失败:", dt["id"])

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)


